package com.example.app.sharescreen;

import android.Manifest;
import android.os.Build;
import android.widget.Toast;

import androidx.annotation.RequiresApi;
import androidx.fragment.app.FragmentActivity;

import com.permissionx.guolindev.PermissionX;

import java.util.ArrayList;
import java.util.List;

public class PermissionManager {
    private FragmentActivity activity;
    private PermissionCallback callback;
    
    public interface PermissionCallback {
        void onPermissionsGranted();
        void onPermissionsDenied(boolean criticalPermissionDenied);
    }
    
    public PermissionManager(FragmentActivity activity, PermissionCallback callback) {
        this.activity = activity;
        this.callback = callback;
    }
    
    @RequiresApi(api = Build.VERSION_CODES.UPSIDE_DOWN_CAKE)
    public void checkAndRequestPermissions() {
        List<String> requiredPermissions = new ArrayList<>();
        requiredPermissions.add(Manifest.permission.RECORD_AUDIO);
        
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
            requiredPermissions.add(Manifest.permission.FOREGROUND_SERVICE_MEDIA_PROJECTION);
        }
        
        PermissionX.init(activity)
                .permissions(requiredPermissions)
                .request((allGranted, grantedList, deniedList) -> {
                    if (allGranted) {
                        if (callback != null) {
                            callback.onPermissionsGranted();
                        }
                    } else {
                        boolean hasCriticalDenial = false;
                        for (String denied : deniedList) {
                            if (denied.equals(Manifest.permission.RECORD_AUDIO)) {
                                hasCriticalDenial = true;
                                break;
                            }
                        }
                        
                        if (callback != null) {
                            callback.onPermissionsDenied(hasCriticalDenial);
                        }
                        
                        if (hasCriticalDenial) {
                            Toast.makeText(activity, "缺少必要权限", Toast.LENGTH_SHORT).show();
                            activity.finish();
                        }
                    }
                });
    }
} 